package com.hyh.manager;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;

import com.hyh.model.Client;
import com.hyh.util.DateUtil;

public class ClientManager {
	
	private Hashtable<String,Client> hashMapClients = new Hashtable<>();
	private Hashtable<String,Long> onlineTime = new Hashtable<>(); 
	private static volatile ClientManager manager;
	private int num=-1;
	
	private ClientManager() {
		new CheckOfflineThread().start();
	}
	
	class CheckOfflineThread extends Thread{
		
		@Override
		public void run() {
			while(true){
				try {
					Enumeration<String> keys = onlineTime.keys();
					long curTime = System.currentTimeMillis();
					while(keys.hasMoreElements()){
						String key=keys.nextElement();
						long time = onlineTime.get(key);
						if(curTime - time>180000){
							hashMapClients.remove(key);
						}
					}
					if(num!=hashMapClients.size()){
						num = hashMapClients.size();
						System.out.println("client num is "+num+" "+DateUtil.getDate());
						Thread.sleep(2000);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public synchronized static ClientManager getInstance(){
		if(manager==null){
			manager = new ClientManager();
		}
		return manager;
	}
	
	public void add(Client client){
		if(client.getId()!=null){
			onlineTime.put(client.getId(), System.currentTimeMillis());
			hashMapClients.put(client.getId(), client);
		}
	}
	
	public void remove(Client client){
		hashMapClients.remove(client);
	}
	
	public Client get(String id){
		return hashMapClients.get(id);
	}
	
	public List<Client> getAll(){
		List<Client> list = new ArrayList<>();
		Enumeration<String> keys = hashMapClients.keys();
		while(keys.hasMoreElements()){
			Client client = hashMapClients.get(keys.nextElement());
			list.add(client);
		}
		return list;
	}
	
}
